package com.jappydb;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.commons.io.IOUtils;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Context of the database. Every database has one single context backing it up.
 * 
 * @author harsh
 */
public class JContext {
	private File mFile;
	private AtomicLong mID;
	private JObject root;
	
	public JContext(File f) throws Exception {
		this.mFile = f;
		this.mID = new AtomicLong(System.currentTimeMillis());
		load();
	}

	public JObject getRoot() {
		return root;
	}

	public void commit() {
		try {
			JSONObject o = root.toJSONObject();
			IOUtils.write(o.toString(2), new FileOutputStream(mFile));
		} catch (Exception e) {
			throw new JException(e.getMessage(), e);
		}
	}
	
	String getId() {
		return Long.toString(mID.getAndIncrement());
	}

	private void load() throws FileNotFoundException, JSONException, IOException {
		JSONObject o = null;
		if (mFile.exists()) {
			o = new JSONObject(IOUtils.toString(new FileInputStream(mFile)));
		} else {
			o = new JSONObject();
		}
		root = new JObject(this, o);
	}

	public String dump() throws JSONException {
		return root.toJSONObject().toString();
	}
}
